<template>
  <div class="container">
    <!-- 搜索栏 -->
    <el-row :gutter="10" class="search-bar">
      <el-col :span="4">
        <el-input
          v-model="searchParams.salesOrderNo"
          placeholder="销售订单号"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-input
          v-model="searchParams.billCode"
          placeholder="单据编码"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-input
          v-model="searchParams.materialCode"
          placeholder="物料编码"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-input
          v-model="searchParams.materialName"
          placeholder="物料名称"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-date-picker
          v-model="searchParams.startDate"
          type="date"
          placeholder="开始日期"
          value-format="YYYY-MM-DD"
          style="width: 100px"
        />
        &nbsp;
        <el-date-picker
          v-model="searchParams.endDate"
          type="date"
          placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 100px"
        />
      </el-col>
    </el-row>
    <div class="action-buttons">
      <el-button type="primary" @click="searchProducts">搜索</el-button>
      <el-button type="primary">单据</el-button>
      <el-button type="success" @click="handlePrint">打印</el-button>
      <el-button
        type="danger"
        @click="handleDelete('批量删除')"
        :disabled="selectedRows.length === 0"
        >批量删除</el-button
      >
      <el-button type="warning" @click="exportData">导出</el-button>
    </div>
    <!-- 功能按钮与分类标签 -->
    <el-row :gutter="8" class="function-buttons"> </el-row>
    <div id="print-content">
      <!-- 数据表格 -->
      <el-table
        @selection-change="handleSelectionChange"
        border
        :data="tableData"
        style="width: 100%"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="procurementMateialsId"
          label="序号"
          width="50"
        ></el-table-column>
        <el-table-column
          prop="salesOrderNo"
          label="跟单编号"
          width="120"
        ></el-table-column>
        <el-table-column prop="orderDeliveryDate" label="订单交期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.orderDeliveryDate) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="billCode"
          label="单据编码"
          width="120"
        ></el-table-column>
        <el-table-column prop="billStatus" label="单据状态" width="80">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.billStatus)">{{
              scope.row.billStatus
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="物料名称"></el-table-column>
        <el-table-column
          prop="materialCode"
          label="物料编码"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="demandquantity"
          label="采购数量"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="procurementNum"
          label="已订数量"
          width="100"
        ></el-table-column>
        <el-table-column prop="billDate" label="单据日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.billDate) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="procurementInstructions"
          label="采购说明"
        ></el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <!-- <el-button
            type="text"
            size="small"
            @click="GetStodto(scope.row.materialCode)"
            >查看</el-button
          > -->
            <el-button
              type="text"
              size="small"
              @click="
                handleDelete(scope.row.procurementMateialsId, [
                  scope.row.materialCode,
                ])
              "
              style="margin-left: 5px"
              >删除</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="upd(scope.row.materialCode)"
              style="margin-left: 5px"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="form1.PageIndex"
        v-model:page-size="form1.PageSize"
        :page-sizes="[1, 3, 15, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="form1.TotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, onMounted, ref } from "vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
const router = useRouter();
const route = useRoute();
const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 5,
  PageIndex: 1,
});
//跳转修改
const upd = (materialCode: string) => {
  router.push({
    path: "/UpdateProcurement",
    query: {
      materialCode: materialCode,
    },
  });
};
//分页
const handleSizeChange = (newSize: number) => {
  form1.PageSize = newSize;
  searchProducts();
};
//分页
const handleCurrentChange = (newPage: number) => {
  form1.PageIndex = newPage; // 正确更新页码
  searchProducts();
};
//显示
const searchProducts = () => {
  axios
    .get("http://localhost:5202/api/Log/GetProcurement", {
      params: {
        PageSize: form1.PageSize,
        PageIndex: form1.PageIndex, // 确保参数名与后端一致
        SalesOrderNo: searchParams.salesOrderNo,
        BillCode: searchParams.billCode,
        MaterialCode: searchParams.materialCode,
        materialName: searchParams.materialName,
        StartDate: searchParams.startDate,
        EndDate: searchParams.endDate,
      },
    })
    .then((res) => {
      tableData.value = res.data.data.list;
      // 注意：后端返回的总记录数是 Data.PageCount，但需要根据总记录数计算总页数
      form1.TotalCount = res.data.data.pageCount; // 总记录数
      form1.PageCount = Math.ceil(form1.TotalCount / form1.PageSize); // 前端计算总页数
    })
    .catch((error) => {
      console.error("获取产品列表失败", error);
    });
};
const searchParams = reactive({
  salesOrderNo: "",
  billCode: "",
  materialCode: "",
  materialName: "",
  startDate: "", // 格式示例：'2023-10-01'
  endDate: "",
});
// 选中的行
// 修改选择处理逻辑（确保ID有效性）
const selectedRows = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};

// 优化后的删除方法
const handleDelete = async (id: any, materialCode: any = []) => {
  try {
    let ids = [];
    let materialCodes = [];

    if (id === "批量删除") {
      // 批量删除逻辑
      if (selectedRows.value.length === 0) {
        ElMessage.warning("请至少选择一条记录");
        return;
      }
      ids = selectedRows.value.map((item) => item.procurementMateialsId);
      materialCodes = selectedRows.value.map((item) => item.materialCode);

      await ElMessageBox.confirm(
        `确定要删除${selectedRows.value.length}条记录？`,
        "警告",
        { type: "warning" }
      );
    } else {
      // 单条删除逻辑
      ids = [id];
      materialCodes = materialCode;

      await ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
        type: "warning",
      });
    }

    // 统一请求处理
    const params = new URLSearchParams();
    params.append("Table", "ProcurementMateials");
    params.append("TableId", "ProcurementMateialsId");
    ids.forEach((id) => params.append("Ids", id.toString()));
    materialCodes.forEach((num) => params.append("MaterialCode", num));

    const res = await axios.delete(
      "http://localhost:5027/api/Log/DeleteProcurement",
      {
        params: params,
        paramsSerializer: (params) => params.toString(), // 确保参数序列化正确
      }
    );

    if (res.data.code === 500) {
      ElMessage.success(res.data.message);
      searchProducts();
      if (id === "批量删除") {
        selectedRows.value = []; // 清空选择
      }
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    if (error !== "cancel") {
      // 忽略用户取消操作
      ElMessage.error(`操作失败: ${error.message}`);
    }
  }
};

onMounted(() => {
  searchProducts();
});

const formatDate = (dateStr: string) => {
  return dayjs(dateStr).format("YYYY-MM-DD");
};

// 搜索表单数据
const formData = ref({
  salesOrderNo: "",
  billCode: "",
  materialCode: "",
  materialName: "",
  dateRange: [],
});
// 打印方法（使用Hiprint）
// 定义 ref
const printTableRef = ref(null);
// 处理表格数据，移除操作列并转换状态列的值
// 处理表格数据，移除操作列并转换状态列的值
const processTableData = (originalData) => {
  return originalData.map((row) => {
    const { id, isDelete, operation, ...newRow } = row; // 移除 id 和操作列
    newRow.status = newRow.status ? "启用" : "停用"; // 转换状态列的值
    console.log("要打印的数据", newRow);
    return newRow;
  });
};

// 打印方法
const handlePrint = () => {
  // 创建新窗口用于打印
  const printWindow = window.open("", "_blank");
  if (!printWindow) {
    ElMessage.error("无法打开打印窗口，请检查浏览器设置");
    return;
  }

  // 获取要打印的表格元素（这里假设 tableData 是表格数据数组）
  const originalTableData = tableData.value;
  const processedTableData = processTableData(originalTableData);

  // 构建打印内容
  printWindow.document.write(
    "<!DOCTYPE html><html><head><title>生产商信息打印</title>"
  );
  printWindow.document.write("<style>");
  printWindow.document.write(`
    @media print {
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
            margin: 20px;
        }
        h1 {
            text-align: center;
            font-size: 20px;
            margin-bottom: 15px;
            color: #333;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            border: 1px solid #ccc; /* 为表格整体添加边框 */
        }
        th, td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: center; /* 水平居中 */
            vertical-align: middle; /* 垂直居中 */
        }
        th {
            background-color: #f0f0f0; /* 表头背景色 */
            font-weight: bold;
            color: #000;
            border-bottom: 2px solid #ccc; /* 加强表头底部边框 */
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
       .footer {
            text-align: center;
            font-size: 10px;
            color: #777;
        }
    }
  `);
  printWindow.document.write("</style></head><body>");
  printWindow.document.write("<h1>生产计划信息打印</h1>");
  printWindow.document.write("<table>");
  printWindow.document.write(
    "<thead><tr><th>序号</th><th>跟单编号</th><th>订单交期</th><th>单据编码</th><th>物料名称</th><th>物料编码</th><th>采购数量</th><th>已订数量</th><th>单据日期</th><th>采购说明</th></tr></thead>"
  );
  printWindow.document.write("<tbody>");
  processedTableData.forEach((row, index) => {
    printWindow.document.write("<tr>");
    printWindow.document.write(`<td>${index + 1}</td>`);
    Object.values(row).forEach((cellValue) => {
      printWindow.document.write(`<td>${cellValue}</td>`);
    });
    printWindow.document.write("</tr>");
  });
  printWindow.document.write("</tbody></table>");
  printWindow.document.write(
    '<div class="footer">打印日期：' +
      new Date().toLocaleDateString() +
      "</div>"
  );
  printWindow.document.write("</body></html>");
  printWindow.document.close();

  // 等待页面加载完成后触发打印
  printWindow.onload = () => {
    printWindow.print();
    // 打印完成后关闭窗口
    printWindow.close();
  };
};

// 表格模拟数据
const tableData = ref([]);
// 单据状态标签类型判断
const getTagType = (status) => {
  if (status === "审核") return "success";
  if (status === "开立") return "warning";
  return "info";
};
//跳转
const Add = () => {
  router.push({
    path: "/AddProcurement",
  });
};
// 导出方法（可在此处添加导出逻辑）
const exportData = () => {
  console.log("触发导出操作");
};
</script>

<style scoped>
.container {
  padding: 10px;
}

.search-bar {
  margin-bottom: 15px;
}

.function-buttons {
  margin-bottom: 10px;
}

.el-table {
  margin-top: 10px;
}

.el-pagination {
  margin-top: 15px;
}
td {
  word-break: break-all; /* 内容自动换行 */
  max-width: 100px; /* 可根据实际情况设置最大宽度 */
}
.container {
  padding: 10px;
}

.search-bar {
  margin-bottom: 15px;
}

.function-buttons {
  margin-bottom: 10px;
}

.el-table {
  margin-top: 10px;
}

.el-pagination {
  margin-top: 15px;
}
td {
  word-break: break-all; /* 内容自动换行 */
  max-width: 100px; /* 可根据实际情况设置最大宽度 */
}
.pagination-container {
  text-align: left; /* 新增样式，使分页控件居左 */
}
</style>